import json
import re
from django import http
from django.shortcuts import render
# Create your views here.
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection
from apps.goods.models import SKU
from apps.users.models import User
from apps.verifications.views import SmsCodeView


class UsernameCountView(View):
    def get(self,request,username):
        # if not re.match('[a-zA-Z0-9_-]{5,20}',username):
        #     return JsonResponse({'code':200,'errmsg':'用户名不满足需求'})
        count = User.objects.filter(username = username).count()
        return JsonResponse({'code':0,'errmsg':'ok','count':count})


class MobileCountView(View):
    """判断手机号是否重复注册"""
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    def post(self, request):
        body_bytes = request.body
        body_str = body_bytes.decode()
        body_dict = json.loads(body_str)

        username = body_dict.get('username')
        password = body_dict.get('password')
        password2 = body_dict.get('password2')
        mobile = body_dict.get('mobile')
        allow = body_dict.get('allow')
        sms_code = body_dict.get('sms_code')

        redis_cli = get_redis_connection('code')
        sms_code_server = redis_cli.get(mobile)
        if not all([username,password, password2,mobile,allow]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        if not re.match('[a-zA-Z_-]{5,20}',username):
            return JsonResponse({'code': 400, 'errmsg': '用户名不满足规则'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误!'})
        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对!'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})
        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': 'allow格式有误!'})
        if not sms_code_server:
            return JsonResponse({'code':400,'errmsg':'短信验证码已失效'})
        if sms_code_server.decode() != sms_code:
            return JsonResponse({'code':400,'errmsg':'短信验证码错误'})
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)

            from django.contrib.auth import login
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '注册失败!'})
        login(request,user)
        return JsonResponse({'code': 0, 'errmsg': '注册成功!'})

#登录
class LogInView(View):
    def post(self,request):
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')

        if not all([username,password]):
            return JsonResponse({'code':400,'errmsg':'参数不全'})

        if re.match('^1[3-9]\d{9}$',username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        from django.contrib.auth import authenticate
        user = authenticate(username = username,password = password)
        if user is None:
            return JsonResponse({'code':400,'errmsg':'账号或密码错误'})
        from django.contrib.auth import login
        login(request,user)

        if remembered :
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)
        response = JsonResponse({'code':0,'errmsg':'ok'})
        response.set_cookie('username',username)

        from apps.carts.utils import merge_cart_cookie_to_redis
        response = merge_cart_cookie_to_redis(request, response)

        return response


from django.contrib.auth import logout
#退出
class LogoutView(View):
    def delete(self,request):
        logout(request)
        response = JsonResponse({'code':0,'errmsg':'ok'})
        response.delete_cookie('username')
        return response

from utils.views import LoginRequiredJSONMixin


class CenterView(LoginRequiredJSONMixin,View):
    def get(self,request):
        info_data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return JsonResponse({'code':0,'errmsg':'ok','info_data':info_data})


class EmailView(View):
    def put(self,request):
        data = json.loads(request.body.decode())
        email = data.get('email')
        user = request.user
        user.email = email
        user.save()
        from django.core.mail import send_mail
        subject='美多验证邮件'
        message=''
        from_email='美多商城<l_iyuan_1@163.com'
        recipient_list = ['l_iyuan_1@163.com','794385447@qq.com']
        from apps.users.utlis import generic_email_verify_token

        token =generic_email_verify_token(request.user.id)
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=%s'%token
        html_message='<p>尊敬的用户您好！</p>' \
                   '<p>感谢您使用美多商城。</p>' \
                   '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                   '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        # send_mail(subject=subject,
        #           message=message,
        #           from_email=from_email,
        #           recipient_list=recipient_list,
        #           html_message=html_message)
        from celery_tasks.email.tasks import celery_send_email
        celery_send_email.delay(subject=subject,
                  message=message,
                  from_email=from_email,
                  recipient_list=recipient_list,
                  html_message=html_message)
        return JsonResponse({'code':0,'errmsg':'ok'})


class EmailVerifyView(View):
    def put(self,request):
        # params = request.GET
        # token = params.get('token')
        token = request.GET.get('token')
        if token is None:
            return JsonResponse({'code':400,'errmsg':'参数缺失'})
        from apps.users.utlis import check_verify_token
        user_id = check_verify_token(token)
        if user_id is None:
            return JsonResponse({'code':400,'errmsg':'参数错误'})
        user = User.objects.get(id = user_id)
        user.email_active = True
        user.save()
        return JsonResponse({'code':0,'errmsg':'ok'})


class UserHistoryView(View):
    def post(self,request):
        user = request.user

        data= json.loads(request.body.decode())
        sku_id = data.get('sku_id')

        try:
            sku= SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此商品'})
        redis_cli = get_redis_connection('history')
        redis_cli.lrem('history_%s'%user.id,0,sku_id)
        redis_cli.lpush('history_%s'%user.id,sku_id)
        redis_cli.ltrim('history_%s'%user.id,0,4)
        return JsonResponse({'code':0,'errmsg':'ok'})

    def get(self,request):
        redis_cli= get_redis_connection('history')

        ids= redis_cli.lrange('history_%s'%request.user.id,0,4)
        history_list= []
        for sku_id in ids:
            sku= SKU.objects.get(id=sku_id)
            history_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        return JsonResponse({'code':0,'errmsg':'ok','skus':history_list})


class ChangePasswordView(LoginRequiredJSONMixin, View):

  def put(self, request):
        user = request.user
        data = json.loads(request.body.decode())
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        new_password2 = data.get('new_password2')

        if not all([old_password, new_password, new_password2]):
           return JsonResponse({'code':400,'errmsg':'缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code':400,'errmsg':'原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code':400,'errmsg':'密码最少8位,最长20位'})

        if new_password != new_password2:
            return http.JsonResponse({'code':400,'errmsg':'两次输入密码不一致'})

        user.set_password(new_password)
        user.save()

        # 清理状态保持信息
        logout(request)
        response = http.JsonResponse({'code':0,'errmsg':'ok'})
        response.delete_cookie('username')
        return response